#define _CRT_SECURE_NO_WARNINGS 1

#include"SqString.h"

void StrAssign(SqString* s, char arr[])
{
	int i = 0;
	for (i = 0; arr[i] != '\0'; i++)
	{
		s->data[i] = arr[i];
	}
	s->length = i;
}

void DispStr(SqString s)
{
	if (s.length > 0)
	{
		int i = 0;
		for (i = 0; i < s.length; i++)
		{
			printf("%c ", s.data[i]);
		}
		printf("\n");
	}
}

int Index(SqString s, SqString t)
{
	int i = 0;
	int j = 0;
	while (i < s.length && j < t.length)
	{
		if (s.data[i] == t.data[j])
		{
			i++;
			j++;
		}
		else
		{
			i = i - j + 1;
			j = 0;
		}
	}
	if (j >= t.length)
	{
		return i - t.length;
	}
	else
	{
		return -1;
	}
}

void GetNext(SqString t, int* next)
{
	int j = 0;
	int k = -1;
	next[0] = -1;
	while (j < t.length - 1)
	{
		if (k == -1 || t.data[j] == t.data[k])
		{
			j++;
			k++;
			next[j] = k;
		}
		else
		{
			k = next[k];
		}
	}
}

int KMPindex(SqString s, SqString t)
{
	int next[MaxSize];
	int i = 0;
	int j = 0;
	GetNext(t, next);
	while (i < s.length && j < t.length)
	{
		if (j == -1 || s.data[i] == t.data[j])
		{
			i++;
			j++;
		}
		else
		{
			j = next[j];
		}
	}
	if (j >= t.length)
	{
		return i - t.length;
	}
	else
	{
		return -1;
	}
}

void GetNextval(SqString t, int* nextval)
{
	int j = 0;
	int k = -1;
	nextval[0] = -1;
	while (j < t.length)
	{
		if (k == -1 || t.data[j] == t.data[k])
		{
			j++;
			k++;
			if (t.data[j] != t.data[k])
			{
				nextval[j] = k;
			}
			else
			{
				nextval[j] = nextval[k];
			}
		}
		else
		{
			k = nextval[k];
		}
	}
}

int KMP_index(SqString s, SqString t)
{
	int nextval[MaxSize];
	int i = 0;
	int j = 0;
	GetNextval(t, nextval);
	while (i < s.length && j < t.length)
	{
		if (j == -1 || s.data[i] == t.data[j])
		{
			i++;
			j++;
		}
		else
		{
			j = nextval[j];
		}
	}
	if (j >= t.length)
	{
		return i - t.length;
	}
	else
	{
		return -1;
	}
}